Security News
Python Overtakes JavaScript as Top Programming Language on GitHub
Python becomes GitHub's top language in 2024, driven by AI and data science projects, while AI-powered security tools are gaining adoption.
The telejson npm package is designed for efficient serialization and deserialization of JavaScript objects, including those with complex types that are not natively supported by JSON, such as Date objects, RegExp, and functions. It is particularly useful for scenarios where you need to transmit complex objects over a network or store them in a way that preserves their type information.
Serialization of complex types
This feature allows the serialization of complex JavaScript types into a string. The code sample demonstrates how to serialize an object containing a Date and a RegExp, which are not natively supported by JSON.
const { stringify } = require('telejson');
const obj = { date: new Date(), regex: /test/i };
const serialized = stringify(obj);
Deserialization with type restoration
This feature enables the deserialization of a string back into a JavaScript object, with the restoration of complex types. The code sample shows how to deserialize a string containing serialized Date and RegExp objects, restoring them to their original types.
const { parse } = require('telejson');
const serialized = '{"date":"2023-04-01T00:00:00.000Z","regex":"/test/i"}';
const obj = parse(serialized);
Function serialization and deserialization
Telejson can serialize and deserialize functions, which is not supported by standard JSON. The code sample demonstrates serializing an object containing a function and then deserializing it, preserving the function.
const { stringify, parse } = require('telejson');
const obj = { func: function add(a, b) { return a + b; } };
const serialized = stringify(obj);
const deserialized = parse(serialized);
Flatted is a package that provides serialization and deserialization of JavaScript objects, including nested ones, using a flat structure. It is similar to telejson but does not support serialization of functions or other complex types like RegExp.
Serialize-javascript offers serialization of JavaScript objects into a string, including support for regular expressions, dates, and functions. It is similar to telejson but focuses more on preventing XSS attacks and does not provide as rich type restoration capabilities.
A library for teleporting rich data to another place.
yarn add telejson
JSON.parse
& JSON.stringify
have limitation by design, because there are no data formats for things like
Also JSON doesn't support cyclic data structures.
This library allows you to pass in data with all of the above properties. It will transform the properties to something that's allowed by the JSON spec whilst stringifying, and then convert back to the cyclic data structure when parsing.
When parsing, class instances will be given the Class's name again. The prototype isn't copied over.
Functions are supported, they are stringified and will be eval-ed when called.
This lazy eval is important for performance.
The eval happens via eval()
Functions are stripped of comments and whitespace.
Obviously calling the function will only really work as expected if the functions were pure the begin with.
Regular expressions just work.
Symbol will be re-created with the same string. (resulting in a similar, but different symbol)
Dates are parsed back into actual Date objects.
DOM Events are processed to extract the internal (hidden) properties, resulting in an object containing the same properties but not being an instance of the original class.
You have 2 choices:
import { stringify, parse } from 'telejson';
const Foo = function () {};
const root = {
date: new Date('2018'),
regex1: /foo/,
regex2: /foo/g,
regex2: new RegExp('foo', 'i'),
fn1: () => 'foo',
fn2: function fn2() {
return 'foo';
},
Foo: new Foo(),
};
// something cyclic
root.root = root;
const stringified = stringify(root);
const parsed = parse(stringified);
stringify and parse do not conform to the JSON.stringify or JSON.parse api. they take an data object and a option object.
OR you can use use the replacer
and reviver
:
import { replacer, reviver } from 'telejson';
import data from 'somewhere';
const stringified = JSON.stringify(data, replacer(), 2);
const parsed = JSON.parse(stringified, reviver(), 2);
notice that both replacer and reviver need to be called! doing the following will NOT WORK:
const stringified = JSON.stringify(data, replacer, 2);
const parsed = JSON.parse(stringified, reviver, 2);
You either pass the options-object to replacer
or as a second argument to stringify
:
replacer({ maxDepth: 10 });
stringify(date, { maxDepth: 10 });
maxDepth
: controls how deep to keep stringifying. When max depth is reach,
objects will be replaced with "[Object]"
, arrays will be replaced with "[Array(<length>)]"
.
default value is 10
This option is really useful if your object is huge/complex, and you don't care about the deeply nested data.
space
: controls how to prettify the output string.
default value is undefined
, no white space is used.
Only relevant when using stringify
.
allowFunction
: When set to false, functions will not be serialized. (default = true)
allowRegExp
: When set to false, regular expressions will not be serialized. (default = true)
allowClass
: When set to false, class instances will not be serialized. (default = true)
allowError
: When set to false, error instances will not be serialized. (default = true)
allowDate
: When set to false, Date objects will not be serialized. (default = true)
allowUndefined
: When set to false, undefined
will not be serialized. (default = true)
allowSymbol
: When set to false, Symbols will not be serialized. (default = true)
lazyEval
: When set to false, lazy eval will be disabled. (default true)
Note: disabling lazy eval will affect performance. Consider disabling it only if you truly need to.
telejson
depends on the collection type Map
. If you support older browsers and devices which may not yet provide these natively (e.g. IE < 11) or which have non-compliant implementations (e.g. IE 11), consider including a global polyfill in your bundled application, such as core-js
or babel-polyfill
.
If you have any suggestions, please open an issue.
All contributions are welcome!
first, build the package:
yarn build
then run the tests:
yarn test
FAQs
A library for teleporting rich data to another place.
The npm package telejson receives a total of 4,427,518 weekly downloads. As such, telejson popularity was classified as popular.
We found that telejson demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Python becomes GitHub's top language in 2024, driven by AI and data science projects, while AI-powered security tools are gaining adoption.
Security News
Dutch National Police and FBI dismantle Redline and Meta infostealer malware-as-a-service operations in Operation Magnus, seizing servers and source code.
Research
Security News
Socket is tracking a new trend where malicious actors are now exploiting the popularity of LLM research to spread malware through seemingly useful open source packages.